package org.example.judge_contest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.RequestParams;
import org.example.judge_common.util.IdWorker;
import org.example.judge_common.util.MyUtils;
import org.example.judge_contest.mapper.ContestRegisterMapper;
import org.example.judge_contest.request.RequestContestAnnounceParams;
import org.example.judge_contest.request.RequestRegisterParams;
import org.example.judge_contest.service.ContestRegisterService;
import org.example.judge_pojo.Contest;
import org.example.judge_pojo.ContestRecord;
import org.example.judge_pojo.ContestRegister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

@Service("ContestRegisterServiceImpl")
public class ContestRegisterServiceImpl extends ServiceImpl<ContestRegisterMapper, ContestRegister> implements ContestRegisterService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;
    @Override
    public ContestRegister getByUserIdAndContestId(String userId, String contestId) {
        QueryWrapper<ContestRegister> contestRegisterQueryWrapper = new QueryWrapper<>();
        contestRegisterQueryWrapper.eq("user_id",userId).eq("contest_id",contestId);
        return this.getOne(contestRegisterQueryWrapper);
    }


    @Override
    public List<ContestRegister> list(String contestId) {
        QueryWrapper<ContestRegister> wrapper = new QueryWrapper<>();
        wrapper.eq("contest_id",contestId).eq("status",0);
        return super.list(wrapper);
    }

    @Override
    public Integer getCountByContest(String id) {
        QueryWrapper<ContestRegister> wrapper = new QueryWrapper<>();
        wrapper.eq("contest_id",id).eq("status",0);
        return super.count(wrapper);
    }

    @Override
    public boolean delete(String contestId, String userId) {
        QueryWrapper<ContestRegister> wrapper = new QueryWrapper<>();
        wrapper.eq("contest_id",contestId).eq("status",0).eq("user_id",userId);

        boolean remove = super.remove(wrapper);
        if(remove){
            //缓存报名人数--
            Object sum = redisTemplate.opsForValue().get(Contest.getRedisRegisterPersonKey(contestId));
            if(sum!=null){
                redisTemplate.opsForValue().set(Contest.getRedisRegisterPersonKey(contestId),((Integer)sum)-1);
            }
        }
        return remove;
    }

    @Override
    public PageResult<ContestRegister> search(RequestRegisterParams params) {
        if(MyUtils.isEmpty(params.getField())){ //默认排序字段
            params.setField("create_time");
        }
        if(MyUtils.isEmpty(params.getOrder())){   //默认排序方式
            params.setOrder(RequestParams.DESC);
        }

        QueryWrapper<ContestRegister> queryWap = new QueryWrapper<>();

        //字段模糊匹配
        if(MyUtils.isNotEmpty(params.getKey())){
            queryWap.and(new Consumer<QueryWrapper<ContestRegister>>() { //隔离or条件
                @Override
                public void accept(QueryWrapper<ContestRegister> problemQueryWrapper) {
                    problemQueryWrapper.like("username",params.getKey()).or().like("school_name",params.getKey());
                }
            });

        }


        //报名用户
        if(MyUtils.isNotEmpty(params.getUserId()))queryWap.eq("user_id",params.getUserId());


        //状态
        if(params.getStatus()!=null&&params.getStatus()>=0&&params.getStatus()<=2){
            queryWap.eq("status",params.getStatus());
        }

        //排序
        queryWap.orderBy(true,"asc".equalsIgnoreCase(params.getOrder()),params.getField());


        //contestId
        if(params.getContestId()!=null&&params.getContestId().length>0){
            queryWap.in("contest_id",params.getContestId());
        }

        //设置分页
        PageHelper.startPage(params.getPage(), params.getSize(),false);
        List<ContestRegister> contests = this.baseMapper.selectList(queryWap);

        //求数据条数
        Integer count = this.baseMapper.selectCount(queryWap);


        return new PageResult<ContestRegister>(count.longValue(),contests);
    }

    @Override
    public Integer getContestCount(String userId) {
        QueryWrapper<ContestRegister> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).eq("status",0);
        wrapper.select("DISTINCT contest_id");
        return super.count(wrapper);
    }

    @Override
    public boolean save(ContestRegister entity) {
        entity.setId(idWorker.nextId().toString());
        entity.setStatus(0);  //默认允许
        entity.setCreateTime(new Date());
        //缓存报名人数++
        Object sum = redisTemplate.opsForValue().get(Contest.getRedisRegisterPersonKey(entity.getContestId()));
        if(sum!=null){
            redisTemplate.opsForValue().set(Contest.getRedisRegisterPersonKey(entity.getContestId()),((Integer)sum)+1);
        }
        return super.save(entity);
    }
}
